package top.xana.acg.common.base.ui

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding

abstract class BaseActivity: AppCompatActivity() {

    companion object{
        const val TAG = "BaseActivity"
    }



    protected val binding by lazy {
        DataBindingUtil.bind<ViewDataBinding>(window.decorView.rootView)
    }


    protected fun <T: ViewDataBinding> getBind() = binding as T


//    protected lateinit var binding: T
    final override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        binding = DataBindingUtil.setContentView<T>(this, getLayoutId())

        setContentView(getLayoutId())
        init()
        initView()
    }


    @LayoutRes
    abstract fun getLayoutId(): Int

    open fun init() {
//        immersive()
    }

    open fun initView() {}

    /* 代码实现沉浸式 */
    private fun immersive() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// 5.0 +
            window.apply {
// 1.
                clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
// 2.
                addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
// 3.
                addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
// 4.
                statusBarColor = Color.TRANSPARENT
            }
            findViewById<ViewGroup>(android.R.id.content).apply {
// 5.
                for (index in 0 until childCount) {
                    val child = getChildAt(index) as? ViewGroup
                    child?.let {
// 6.
//                        it.fitsSystemWindows = true
                        it.clipToPadding = true
                    }
                }
            }
        } else {
// 7
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
    }


    private val t by lazy {
        Toast.makeText(this, null, Toast.LENGTH_SHORT).apply { addCallback(object :
            Toast.Callback() {
            override fun onToastHidden() {
                super.onToastHidden()
                Log.e(TAG, "隐藏")
            }

            override fun onToastShown() {
                super.onToastShown()
                Log.e(TAG, "显示")

            }
        }) }
    }

    fun toast(msg: CharSequence) = run {
        t.cancel()
        t.setText(msg)
        t.show()
    }


    inline fun View.text() = (this as TextView).text

    fun <T : Class<out Context>> navTo(ctxClz: T) {
        startActivity(Intent(applicationContext, ctxClz))
    }
}